package com.yonyou.pmclouds.basecom.ref.impl;

import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.ref.itf.ReferenceCheckOfBusiness;
import com.yonyou.pmclouds.basecom.ref.itf.ReferenceChecker;
import org.apache.commons.lang3.ArrayUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ReferenceCheckerImpl implements ReferenceChecker {
    private Map<String, List<ReferenceCheckOfBusiness>> codeCheckMap = new HashMap<>(128);

    @Override
    public boolean checkReferenced(String bdCode, String[] keys) throws BusinessException {
        List<ReferenceCheckOfBusiness> referCheckers = codeCheckMap.get(bdCode);
        if (referCheckers == null || referCheckers.size() == 0) {
            return false;
        }
        for (ReferenceCheckOfBusiness checker : referCheckers) {
            if (checker.checkReferenced(bdCode, keys)) {
                //  可以考虑多线程
                return true;
            }
        }
        return false;
    }

    public void addChecker(ReferenceCheckOfBusiness checker) {
        String[] codes = checker.getReferenceCode();
        if (ArrayUtils.isEmpty(codes)) {
            return;
        }
        for (String code : codes) {
            List<ReferenceCheckOfBusiness> checkers = codeCheckMap.get(code);
            if (checkers == null) {
                checkers = new ArrayList<>();
                codeCheckMap.put(code, checkers);
            }
            checkers.add(checker);
        }
    }
}
